package com.aruba.shaderapplication;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Shader;
import android.util.AttributeSet;

/**
 * 霓虹灯文字
 */
public class LinearGradientTextView extends android.support.v7.widget.AppCompatTextView {
    private LinearGradient linearGradient;
    private int gradientCount = 3;
    private int FACTOR = 20;
    private int postix = 0;
    private float textMaxWidth;
    private Matrix matrix = new Matrix();

    public LinearGradientTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        String text = getText().toString();
        textMaxWidth = getPaint().measureText(text);
        float onceWidth = textMaxWidth / text.length() * gradientCount;

        linearGradient = new LinearGradient(-onceWidth, 0, 0, 0, new int[]{getCurrentTextColor(), 0xff000000, getCurrentTextColor()},
                null, Shader.TileMode.CLAMP);
        getPaint().setShader(linearGradient);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        postix += FACTOR;
        if (postix > textMaxWidth || postix < -1) {
            FACTOR = -FACTOR;
        }
        matrix.setTranslate(postix, 0);
        linearGradient.setLocalMatrix(matrix);

        postInvalidateDelayed(50);
    }
}
